<?php
/*
 Plugin Name: TungttOpenID
 Plugin URI: http://wordpress.org/extend/plugins/openid
 Description: Allows the use of OpenID for account registration, authentication, and commenting.  Also includes an OpenID provider which can turn WordPress author URLs into OpenIDs.
 Author: DiSo Development Team
 Author URI: http://diso-project.org/
 Version: 3.3.4
 License: Dual GPL (http://www.fsf.org/licensing/licenses/info/GPLv2.html) and Modified BSD (http://www.fsf.org/licensing/licenses/index_html#ModifiedBSD)
 Text Domain: openid
 */

// run activation function if new revision of plugin


//add_action('wp_head', 'redirect_ok');
// function redirect_ok(){
// 	echo '<script>
// 			function hihi(){
// 				window.open("http://tuoitre.vn","_blank","width: 100, height: 200");
// 			}
// 			</script>
// 			';
// 	echo "<div id='okok' onclick='hihi();'>clickvao di </div>";
	
// 		$creds = array();
// 		$creds['user_login'] = "admin";
// 		$creds['user_password'] = "fsda";
// 		$creds['remember'] = true;
		
// 		// TODO do we deprecate the wp_authentication action?
// 		do_action_ref_array('wp_authenticate', array(&$creds['user_login'], &$creds['user_password']));
// 		$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
		
// 		$user = wp_authenticate($creds['user_login'], $creds['user_password']);
// 		wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);		
// }

require_once 'openid.php';
const DOMAIN_NAME ="localhost";
const CALLBACK_URL ="http://yourstyle.name/yourstyle/raovat/";
const URL_CONTROLLER = "http://yourstyle.name/yourstyle/raovat/?page_id=11";
const IDPage = "11";

add_action('wp_head', 'oauthFacebookLogin');
add_action('wp_head', 'openIdGoogleLogin');
add_action('wp_head', 'openIdYahooLogin');

function openIdGoogleLogin(){
	global $wpdb;
	if ( is_user_logged_in() ) { return; }
	if ( !is_page(IDPage) ) { return; }
	
	$urlGoogle ="";
	$openidGoogle = new LightOpenID(DOMAIN_NAME);
	if(!$openidGoogle->mode) {
		$openidGoogle->identity = 'https://www.google.com/accounts/o8/id';
		$openidGoogle->required = array('contact/email', 'pref/language', 'namePerson/friendly','namePerson', 'birthDate', 'person/gender');
		$urlGoogle = $openidGoogle->authUrl();
		
		echo "<script>
		function loginByGoogle(){
			var w = 550;
			var h = 500;
			var url = '".$urlGoogle."';
		
			var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
		    var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
		
		    var left = ((screen.width / 2) - (w / 2)) + dualScreenLeft;
		    var top = ((screen.height / 2) - (h / 2)) + dualScreenTop;
			window.open(url, '_blank',  'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
		}
		</script>";
		
	} elseif($openidGoogle->mode == 'cancel') {
		echo "<script>
			self.close ();
			window.opener.location.href='".CALLBACK_URL."';
		</script>";
		
	} else {
		$Googledata = $openidGoogle->getAttributes();
		$username = "";
		$pass ="";
		//check user is exit or not
		$myrows = $wpdb->get_results( "SELECT *
										FROM ".$wpdb->users."
										WHERE user_email='".$Googledata['contact/email']."'");

		if(sizeof($myrows) == 0){
			$dataEmail = explode("@", $Googledata['contact/email']);
			$username = $dataEmail[0];
			$password = "yourstyle!@#".rand();
			$pass =md5($password); 

			//insert user to database.
			$uid = wp_insert_user( array ('user_login' => $dataEmail[0],
					'display_name' => $Googledata['namePerson'],
					'user_email' => $Googledata['contact/email'],
					'user_pass' => $password)) ;
		}
		else{
			$uid =$myrows[0]->ID;
			$username = $myrows[0]->user_login;
			$pass = $myrows[0]->user_pass;
		}
			
		$creds = array('user_login' => $username,
				'user_password' =>$pass,
				'remember' => true
		);
			
		// TODO do we deprecate the wp_authentication action?
		do_action_ref_array('wp_authenticate', array(&$creds['user_login'], &$creds['user_password']));
		$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
			
		$user = wp_authenticate($creds['user_login'], $creds['user_password']);
		//wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
		wp_setcookie( $creds['user_login'], $creds['user_password'], true, "", "", true );
		
		echo "<script>
			self.close ();
			window.opener.location.href='".CALLBACK_URL."';
		</script>";
	}
}

function openIdYahooLogin(){
	if ( is_user_logged_in() ) { return; }
	if ( !is_page(IDPage) ) { return; }
	$urlYahoo ="";
	$openidYahoo = new LightOpenID(DOMAIN_NAME);
	$urlGetData ="";
	if(!$openidYahoo->mode) {
		$openidYahoo->identity = 'https://me.yahoo.com';
		$openidYahoo->required = array('contact/email', 'pref/language', 'namePerson/friendly','namePerson', 'birthDate', 'person/gender');
		$urlYahoo = $openidYahoo->authUrl();
	
		echo "<script>
		function loginByYahoo(){
			var w = 550;
			var h = 500;
			var url = '".$urlYahoo."';
		
			var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
		    var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
		
		    var left = ((screen.width / 2) - (w / 2)) + dualScreenLeft;
		    var top = ((screen.height / 2) - (h / 2)) + dualScreenTop;
			window.open(url, '_blank',  'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
		}
		</script>";
	} elseif($openidYahoo->mode == 'cancel') {
		echo "<script>
			self.close ();
			window.opener.location.href='".CALLBACK_URL."';
		</script>";
		
	} else {
		$Yahoodata = $openidYahoo->getAttributes();

		//check user is exit or not
		$myrows = $wpdb->get_results( "SELECT *
											FROM ".$wpdb->users."
											WHERE user_email='".$Yahoodata['contact/email']."'");
		if( sizeof($myrows) == 0){
			$dataEmail = explode("@", $Yahoodata['contact/email']);
			$username = $dataEmail[0];
			$password = "yourstyle!@#".rand();
			$pass = md5($password);
			//insert user to database.
			$uid = wp_insert_user( array ('user_login' => $username,
					'display_name' => $Yahoodata['namePerson'],
					'user_email' => $Yahoodata['contact/email'],
					'user_pass' => $pass)) ;
		}
		else{
			$uid =$myrows[0]->ID;
			$username = $myrows[0]->user_login;
			$pass = $myrows[0]->user_pass;
		}

		$creds = array();
		$creds['user_login'] = $username;
		$creds['user_password'] = $pass;
		$creds['remember'] = true;
		
		// TODO do we deprecate the wp_authentication action?
		do_action_ref_array('wp_authenticate', array(&$creds['user_login'], &$creds['user_password']));
		$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
			
		$user = wp_authenticate($creds['user_login'], $creds['user_password']);
		wp_setcookie( $creds['user_login'], $creds['user_password'], true, "", "", true );
		
		echo "<script>
			self.close ();
			window.opener.location.href='".CALLBACK_URL."';
		</script>";
	}	
}

function oauthFacebookLogin(){
	if ( is_user_logged_in() ) { return; }
	if ( !is_page(IDPage) ) { return; }
	
	global $wpdb;
	$code = $_GET["code"];
	if(isset($_GET["code"])){
		//echo "Code = ".$code."<br/>";
		$uri = URL_CONTROLLER;
		$uri = utf8_encode($uri);
		$token_url = "https://graph.facebook.com/oauth/access_token?client_id=618836824809238&client_secret=25e84a57bdd0b1c8ac5cca91e608c123&code=".$code."&redirect_uri=".$uri;
		$response = @file_get_contents($token_url);
		$params = null;
		parse_str($response, $params);
		$graph_url = "https://graph.facebook.com/me?access_token=".$params['access_token'];
		$user = json_decode(file_get_contents($graph_url));
		$email = $user->email;
		//check user is exit or not
		$myrows = $wpdb->get_results( "SELECT *
										FROM ".$wpdb->users."
										WHERE user_email='".$email."'");
		
		if(sizeof($myrows) == 0){
			$dataEmail = explode("@", $email);
			$username = $dataEmail[0];
			$password = "yourstyle!@#".rand();
			$pass = md5($password);
		
			//insert user to database.
			$uid = wp_insert_user( array ('user_login' => $dataEmail[0],
					'display_name' => $username,
					'user_email' => $email,
					'user_pass' => $password)) ;
		}
		else{
			$uid =$myrows[0]->ID;
			$username = $myrows[0]->user_login;
			$pass = $myrows[0]->user_pass;
		
		}
			
		$creds = array('user_login' => $username,
				'user_password' =>$pass,
				'remember' => true
		);
		// TODO do we deprecate the wp_authentication action?
		do_action_ref_array('wp_authenticate', array(&$creds['user_login'], &$creds['user_password']));
		$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
			
		$user = wp_authenticate($creds['user_login'], $creds['user_password']);
		//wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
		wp_setcookie( $creds['user_login'], $creds['user_password'], true, "", "", true );
		
		echo "<script>
			self.close ();
			window.opener.location.href='".CALLBACK_URL."';
		</script>";
	}
}



